<template>
  <div>
    <div id="topology_chart" style="width: 100vw; height: 100vh;" />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'



// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('topology_chart');
  const myChart = echarts.init(chartDom);

  const option = {
    title: {
      text: 'World Population'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',  // 增加底部边距，为x轴标签留出空间
      containLabel: true
    },
    xAxis: {  // x轴改为类目轴
      type: 'category',
      data: ['Brazil', 'Indonesia', 'USA', 'India', 'China', 'World']
    },
    yAxis: {  // y轴改为数值轴
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    series: [
      {
        name: '2011',
        type: 'bar',
        data: [18203, 23489, 29034, 104970, 131744, 630230]
      },
      {
        name: '2012',
        type: 'bar',
        data: [19325, 23438, 31000, 121594, 134141, 681807]
      }
    ]
  };


  myChart.setOption(option);
  myChart.resize();

  window.addEventListener('resize', () => {
    myChart.resize();
  });

  return myChart;
};

// 格式化标签
const formatLabel = (params) => {
  let res = '';
  if (params.data.level === 1) {
    res += `{a|部门：${params.data.datas.department}}\n{b|描述：${params.data.datas.description}}`;
  } else if (params.data.level === 2) {
    res += `{c|部门：${params.data.datas.department}}\n{c|描述：${params.data.datas.description}}`;
  } else {
    res += `{c|部门：${params.data.datas.department}}\n{c|职责：${params.data.datas.description}}`;
  }

  return res;
};

// 组件挂载后初始化图表
let chartInstance;

onMounted(() => {
  nextTick(() => {
    chartInstance = initChart();
  });
});

// 清除事件监听器，防止内存泄漏
onUnmounted(() => {
  window.removeEventListener('resize', () => chartInstance?.resize());
  chartInstance?.dispose();
});
</script>

<style scoped>
/* 可以在这里添加CSS样式 */
</style>
